package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.entity.Book;
import com.example.universitylibraryback.pipeline.BorrowContext;
import com.example.universitylibraryback.pipeline.Filter;
import com.example.universitylibraryback.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.BlockingQueue;

/**
 * 图书状态校验过滤器
 * 负责校验图书的可借阅状态
 */
@Component
public class BookStatusFilter implements Filter<BorrowContext>, Runnable {
    private BlockingQueue<BorrowContext> inputQueue;
    private BlockingQueue<BorrowContext> outputQueue;

    @Autowired
    private BookService bookService;

    @Override
    public void process(BlockingQueue<BorrowContext> inputQueue, BlockingQueue<BorrowContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                BorrowContext context = inputQueue.take();
                if (context.isValid()) {
                    String bookId = context.getBookId();
                    Book book = bookService.findBookById(bookId);
                    
                    if (book == null) {
                        context.setValid(false);
                        context.setErrorMsg("图书不存在");
                    } else if (!"可借".equals(book.getBookStatus()) || book.getStock() <= 0) {
                        context.setValid(false);
                        context.setErrorMsg("图书不可借");
                    } else {
                        // 图书状态校验通过
                        context.setErrorMsg("图书状态校验通过");
                    }
                }
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("BookStatusFilter中断");
        }
    }
}